﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Net.NetworkInformation;

namespace BattleShips.GameServers {
    public partial class CreateServers : Form {
        public CreateServers() {
            InitializeComponent();
        }

        public Action<IPAddress, int> CreateServer { get; set; }

        private void button1_Click(object sender, EventArgs e) {
            if (txtIPAddress.Text != String.Empty && txtPort.Text != String.Empty) {
                IPAddress serverIP;
                int port = 0;
                if (Int32.TryParse(txtPort.Text, out port) && IPAddress.TryParse(txtIPAddress.Text, out serverIP)) {
                    if (PortAvailable(port)) {
                        CreateServer(serverIP, port);
                    } else {
                        lblPortError.Visible = true;
                        lblPortError.Text = "Port is not open or is used by another application.";
                    }
                }
            }
        }
        private void CreateServers_Load(object sender, EventArgs e) {
            if (GetPublicIP() != null) {
                txtIPAddress.Text = GetPublicIP();
            } else {
                lblIPAddrError.Visible = true;
                lblIPAddrError.Text += "Can't get your IP. You can find by yourself on internet then type it here.";
            }
        }

        public string GetPublicIP() {
            String direction = "";
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            using (WebResponse response = request.GetResponse())
            using (StreamReader stream = new StreamReader(response.GetResponseStream())) {
                direction = stream.ReadToEnd();
            }

            //Search for the ip in the html
            int first = direction.IndexOf("Address: ") + 9;
            int last = direction.LastIndexOf("</body>");
            direction = direction.Substring(first, last - first);

            return direction;
        }

        private bool PortAvailable(int port) {
            bool isAvailable = true;

            IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();

            foreach (IPEndPoint endpoint in tcpConnInfoArray) {
                if (endpoint.Port == port) {
                    isAvailable = false;
                    break;
                }
            }
            return isAvailable;
        }

    }
}
